package com.zxl.permission.service;


import com.alibaba.fastjson.JSONObject;
import com.zxl.permission.dao.LoginDao;
import com.zxl.permission.entity.Token;
import com.zxl.permission.entity.User;
import com.zxl.permission.utils.TokenGenerater;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.List;

@Service
@Transactional
public class LoginService {
    @Autowired
    private LoginDao loginDao;

    private long EXPIRETIME = 1000 * 60 * 60 * 2; // 两个小时token过期

    public JSONObject login(String username, String password, HttpServletResponse rsp) {
        // 检查用户名密码
        List<String> storedPassword = loginDao.getPasswordFromUsername(username);
        if (storedPassword == null || storedPassword.size() == 0) {
            JSONObject res = new JSONObject();
            res.put("code", 200);
            res.put("msg", "unknown user");
            return res;
        }
        if (!storedPassword.get(0).equals(password)) {
            JSONObject res = new JSONObject();
            res.put("code", 201);
            res.put("msg", "wrong password");
            return res;
        }

        // 更新登录态
        List<Token> tokenInfo = loginDao.getTokenFromUsername(username);
        String token;
        if (tokenInfo.size() == 0) {   // 用户token未缓存，创建
            token = TokenGenerater.encrypt(username);
            Timestamp cur_time = new Timestamp(System.currentTimeMillis());
            loginDao.createTokenFromUsername( username, token, cur_time, cur_time);
        } else {    // 用户token已缓存，鉴定
            Timestamp cur_time = new Timestamp(System.currentTimeMillis());
            if ((cur_time.getTime() - tokenInfo.get(0).active_time.getTime()) > EXPIRETIME) {  // token已过期
                loginDao.deleteTokenFromUsername(username);
                token = TokenGenerater.encrypt(username);
                loginDao.createTokenFromUsername(username, token, cur_time, cur_time);
            } else {    // token仍有效
                token = tokenInfo.get(0).token;
                loginDao.updateActiveTime(username, cur_time);
            }
        }

        // 设置cookie
        Cookie cookie = new Cookie("token", token);
        cookie.setMaxAge(2 * 60 * 60);  //cookie 持久化时间
        rsp.addCookie(cookie);

        // 组装返回包
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "success");

        return res;
    }

    public JSONObject logout(String username, String token, HttpServletResponse rsp) {
        // 校验登录态
        //TODO: 校验登录态

        // 清除token
        loginDao.deleteTokenFromUsername(username);

        // 清除cookie
        Cookie cookie = new Cookie("token", null);
        cookie.setMaxAge(2 * 60 * 60);  //cookie 持久化时间
        rsp.addCookie(cookie);

        // 组装回包
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "success");

        return res;
    }


    public String register(User user) {
        return "";
    }


}
